// pages/order/details.js
const WXAPI = require('../../miniprogram_npm/apifm-wxapi/index')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    orderId: '',
    orderInfo: {},
    showExitDialog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        orderId: options.id
      })
      this.loadOrderDetail()
    } else {
      wx.showToast({
        title: '订单ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadOrderDetail().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '订单详情',
      path: `/pages/order/details?id=${this.data.orderId}`
    }
  },

  /**
   * 加载订单详情
   */
  async loadOrderDetail() {
    this.setData({ loading: true })
    
    try {
      // 使用模拟数据，实际项目中应调用真实API
      const mockData = this.getMockOrderDetail(this.data.orderId)
      
      this.setData({
        orderInfo: mockData,
        loading: false
      })
      
      // 实际项目中的API调用
      // const res = await WXAPI.orderDetail({
      //   token: wx.getStorageSync('token'),
      //   orderId: this.data.orderId
      // })
      // if (res.code === 0) {
      //   this.setData({
      //     orderInfo: res.data,
      //     loading: false
      //   })
      // }
      
    } catch (error) {
      console.error('加载订单详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  /**
   * 获取模拟订单详情数据
   */
  getMockOrderDetail(orderId) {
    const mockOrders = {
      '1': {
        id: '1',
        orderNo: 'PD202309110001',
        wxOrderNo: '4200001234567890123456789',
        productName: '派对套餐A',
        productDesc: '包含饮料、小食、装饰用品',
        productImage: '/images/party1.png',
        price: '299.00',
        quantity: 1,
        payAmount: '299.00',
        createTime: '2023-09-11 14:30:00',
        payTime: '2023-09-11 14:31:25',
        status: 'queue',
        queuePosition: 5,
        merchantName: '欢乐派对屋',
        merchantAddress: '北京市朝阳区三里屯太古里南区',
        merchantPhone: '010-12345678'
      },
      '2': {
        id: '2',
        orderNo: 'PD202309110002',
        wxOrderNo: '4200001234567890123456790',
        productName: '生日派对套餐',
        productDesc: '生日蛋糕、气球、彩带等',
        productImage: '/images/party2.png',
        price: '199.00',
        quantity: 1,
        payAmount: '199.00',
        createTime: '2023-09-11 10:15:00',
        payTime: '2023-09-11 10:16:30',
        status: 'queue',
        queuePosition: 12,
        merchantName: '童趣生日会',
        merchantAddress: '北京市海淀区中关村大街1号',
        merchantPhone: '010-87654321'
      },
      '3': {
        id: '3',
        orderNo: 'PD202309100001',
        wxOrderNo: '4200001234567890123456791',
        productName: '免费体验套餐',
        productDesc: '新用户专享免费体验',
        productImage: '/images/free1.png',
        price: '99.00',
        quantity: 1,
        payAmount: '99.00',
        createTime: '2023-09-10 16:20:00',
        payTime: '2023-09-10 16:21:15',
        status: 'free',
        freeTime: '2023-09-10 18:30:00',
        freeReason: '排队免单活动',
        discountAmount: '99.00',
        merchantName: '新手体验店',
        merchantAddress: '北京市西城区王府井大街100号',
        merchantPhone: '010-11111111'
      },
      '4': {
        id: '4',
        orderNo: 'PD202309090001',
        wxOrderNo: '4200001234567890123456792',
        productName: '派对套餐B',
        productDesc: '因故取消，已退款',
        productImage: '/images/party3.png',
        price: '399.00',
        quantity: 1,
        payAmount: '399.00',
        createTime: '2023-09-09 12:00:00',
        payTime: '2023-09-09 12:01:45',
        status: 'refund',
        refundTime: '2023-09-09 15:30:00',
        refundReason: '用户主动取消',
        refundAmount: '399.00',
        refundStatus: '退款成功',
        merchantName: '豪华派对厅',
        merchantAddress: '北京市东城区东单北大街88号',
        merchantPhone: '010-22222222'
      }
    }
    
    return mockOrders[orderId] || mockOrders['1']
  },

  /**
   * 显示退出排队确认弹窗
   */
  showExitQueueDialog() {
    this.setData({
      showExitDialog: true
    })
  },

  /**
   * 确认退出排队
   */
  async confirmExitQueue() {
    this.setData({
      showExitDialog: false
    })
    
    wx.showLoading({
      title: '处理中...'
    })
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 实际项目中的API调用
      // const res = await WXAPI.exitQueue({
      //   token: wx.getStorageSync('token'),
      //   orderId: this.data.orderId
      // })
      
      wx.hideLoading()
      wx.showToast({
        title: '已退出排队，优惠券已发放',
        icon: 'success'
      })
      
      // 刷新订单详情
      setTimeout(() => {
        this.loadOrderDetail()
      }, 1500)
      
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
    }
  },

  /**
   * 取消退出排队
   */
  cancelExitQueue() {
    this.setData({
      showExitDialog: false
    })
  },

  /**
   * 联系商家
   */
  contactMerchant() {
    const phone = this.data.orderInfo.merchantPhone
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      })
    } else {
      wx.showToast({
        title: '商家电话不可用',
        icon: 'none'
      })
    }
  },

  /**
   * 评价订单
   */
  rateOrder() {
    wx.navigateTo({
      url: `/pages/rate/index?orderId=${this.data.orderId}`
    })
  },

  /**
   * 再次购买
   */
  reorder() {
    wx.navigateTo({
      url: `/pages/product/detail?id=${this.data.orderInfo.productId}`
    })
  }
})